package com.skymxc.wandroidtodo.data.net;

import java.security.Key;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * <p>
 *
 * </p>
 *
 * @author 孟祥超
 * <p>
 * date: 2021/12/1  7:27 上午
 */
public class RetrofitManager {

    private static class RetrofitManagerHolder {
        private static final RetrofitManager INSTANCE = new RetrofitManager();
    }

    public static RetrofitManager getManager() {
        return RetrofitManagerHolder.INSTANCE;
    }

    private Retrofit retrofit;

    public Retrofit getRetrofit() {
        if (null != retrofit) return retrofit;
        retrofit = new Retrofit.Builder()
                .baseUrl("https://www.wanandroid.com/")
                .client(getOkhttpClient())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        return retrofit;
    }

    private CookieManager cookieManager = new CookieManager();

    private OkHttpClient getOkhttpClient() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        // cookie 管理
        builder.cookieJar(cookieManager);
        // 超时时长
        builder.connectTimeout(30, TimeUnit.SECONDS);
        builder.readTimeout(30, TimeUnit.SECONDS);
        //log
        builder.addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY));
        return builder.build();
    }

    public void clearCookie() {
        cookieManager.removeCookie();
    }
}
